package intranet.client;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * 
 * @author Robin TROADEC
 *
 */
public class AdminCourse extends HorizontalPanel
{
	
	protected MenuBar	menu;
	protected Command	cmdUser, cmdCourse, cmdSubject;
	protected MenuItem	menuUser,menuCourse, menuSubject;
	protected VerticalPanel centerPanel,courseListPan,courseInfoPan,courseDialog;
	protected FlowPanel courseSubjectButton,courseInfoName,courseInfoCode;
	protected HorizontalPanel  courseSubjectPan;
	protected ListBox courseList,courseSubjectWithList,courseSubjectList;
	protected PushButton courseAdd,courseRem,courseAddSubj,courseRemSubj,courseValid;
	protected ValidTextBox courseName,courseAddTitle,courseCode,courseAddCode;
	protected DialogBox courseAddDialog;
	protected Button courseValidAdd,courseCancel;
	protected HorizontalPanel courseLabel,courseButton;
	protected int test =0;
	
	private static final String SERVER_ERROR = "An error occurred while "
		+ "attempting to contact the server. Please check your network "
		+ "connection and try again.";

	
	private final DataBaseServiceAsync dataService = GWT
	.create(DataBaseService.class);
	


	/**
	 * Creation d'un panel d'administration des filières
	 * @param La session courante
	 */
	public AdminCourse(Session s)
	{
		courseListPan = new VerticalPanel();
		courseListPan.setHorizontalAlignment(ALIGN_CENTER);
		
		courseButton = new HorizontalPanel();
		

		//Panel de boutton ajout/suppr course
		courseAdd = new PushButton(new Image("add.png"));
		courseAdd.setSize("20px", "20px");
		courseAdd.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				//Préparation Dialog
				courseAddDialog = new DialogBox();
				courseAddDialog.setGlassEnabled(true);
				courseAddDialog.setAnimationEnabled(true);
				courseAddDialog.setPopupPosition(600, 250);
				courseDialog = new VerticalPanel();
				
				courseValidAdd = new Button("Ajouter");
				courseValidAdd.addClickHandler(new ClickHandler()
				{
					public void onClick(ClickEvent event)
					{
						if ((!courseAddCode.getText().equals(""))&&(!(courseAddTitle.getText().equals(""))))
						{
							
							String r = "insert into course (course_name,course_code) values('"+courseAddTitle.getText()+"','"+courseAddCode.getText()+"')";
							dataService.insert(r, new AsyncCallback<Integer>()
							{
								public void onFailure(Throwable caught)
								{}

								public void onSuccess(Integer result)
								{
									courseAddDialog.hide();
									courseAddCode.removeStyleName("error");
									courseAddTitle.removeStyleName("error");
												
									initListe();
									
								}
							});
						}
						else
						{
							if (courseAddCode.getText().equals(""))
								courseAddCode.addStyleName("error");
							else
								courseAddCode.removeStyleName("error");
							if (courseAddTitle.getText().equals(""))
								courseAddTitle.addStyleName("error");
							else
								courseAddTitle.removeStyleName("error");
						}
						
					}
				});
					
					
				courseCancel = new Button("Annuler");
					courseCancel.addClickHandler( new ClickHandler()
					{
						
						public void onClick(ClickEvent event)
						{
							courseAddDialog.hide();						
						}
					});
					
				courseAddTitle = new ValidTextBox();
				courseAddCode = new ValidTextBox();
				validEnabled(false);
				
				courseDialog.add(new HTML("Nom de la filière"));
				courseDialog.add(courseAddTitle);
				courseDialog.add(new HTML("Code de la filière"));
				courseDialog.add(courseAddCode);
				courseDialog.add(courseValidAdd);
				courseDialog.add(courseCancel);
				
				courseAddDialog.add(courseDialog);
				courseAddDialog.show();				
			}
		});
		
		courseRem = new PushButton(new Image("delete.png"));
		courseRem.setSize("20px", "20px");
		courseRem.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				if (Window.confirm("Êtes-vous sûr de vouloir supprimer cette filière? Toutes les données concernant cette filières seront perdues" ))
				{
					if (courseList.getSelectedIndex()>=0)
					{	
						String r="delete from subject_course where course_id='"+courseList.getValue(courseList.getSelectedIndex())+"'";
						
						dataService.delete(r,new AsyncCallback<Integer>()
						{
							public void onSuccess(Integer result)
							{
								String r="delete from course where course_id='"+courseList.getValue(courseList.getSelectedIndex())+"'";
								
								dataService.delete(r, new AsyncCallback<Integer>()
								{
									public void onFailure(Throwable caught)
									{}
									public void onSuccess(Integer result)
									{
										courseList.removeItem(courseList.getSelectedIndex());
										courseName.setText("");
										courseCode.setText("");
										courseSubjectList.clear();
										courseSubjectWithList.clear();
										validEnabled(false);
									}
								});
							}
							
							public void onFailure(Throwable caught)
							{}
						});	
					}	
				}
			}
		});
		courseButton.add(courseAdd);
		courseButton.add(courseRem);	
		

		//Bouton d'ajout suppr des matieres a la filiere
		courseAddSubj = new PushButton(new Image("right.png"));
		courseAddSubj.setSize("40px", "40px");
		courseAddSubj.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				if (courseSubjectList.getSelectedIndex()>=0)
				{
					String name = courseSubjectList.getItemText(courseSubjectList.getSelectedIndex());
					String value = courseSubjectList.getValue(courseSubjectList.getSelectedIndex());
					courseSubjectWithList.addItem(name, value);
					courseSubjectList.removeItem(courseSubjectList.getSelectedIndex());
				}	
			}
		});
		
		courseRemSubj = new PushButton(new Image("left.png"));
		courseRemSubj.setSize("40px", "40px");
		courseRemSubj.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				if (courseSubjectWithList.getSelectedIndex()>=0)
				{
					String name = courseSubjectWithList.getItemText(courseSubjectWithList.getSelectedIndex());
					String value = courseSubjectWithList.getValue(courseSubjectWithList.getSelectedIndex());
					courseSubjectList.addItem(name, value);
					courseSubjectWithList.removeItem(courseSubjectWithList.getSelectedIndex());
				}			
			}
		});

		courseSubjectButton = new FlowPanel();
		courseSubjectButton.add(courseAddSubj);
		courseSubjectButton.add(courseRemSubj);
		
		courseSubjectList = new ListBox();
		courseSubjectList.setSize(Window.getClientWidth()*16/20*1/3+"px", Window.getClientHeight()*9/10*2/3+"px");
		courseSubjectList.setVisibleItemCount(10);
		courseSubjectWithList = new ListBox();
		courseSubjectWithList.setSize(Window.getClientWidth()*16/20*1/3+"px", Window.getClientHeight()*9/10*2/3+"px");
		
		courseSubjectWithList.setVisibleItemCount(10);
		
		courseSubjectPan = new HorizontalPanel();
		courseSubjectPan.add(courseSubjectList);
		courseSubjectPan.add(courseSubjectButton);
		courseSubjectPan.add(courseSubjectWithList);
		

		//Panel des infos
		courseInfoPan = new VerticalPanel();
		courseInfoPan.setHorizontalAlignment(ALIGN_CENTER);
		courseInfoName = new FlowPanel();
		courseInfoCode = new FlowPanel();
		courseName = new ValidTextBox();
		courseCode = new ValidTextBox();
		courseValid = new PushButton("Valider");
	 		courseValid.setSize("50px", "20px");
 		courseValid.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				final ArrayList<String> tp = new ArrayList<String>();
				for (int i =0;i<courseSubjectWithList.getItemCount();i++)
					tp.add(courseSubjectWithList.getValue(i));
				
				if ((!courseCode.getText().equals(""))&&(!courseName.getText().equals("")))
				{
					String r = "update course set course_code='"+courseCode.getText()+"',course_name='"+courseName.getText()+"' where course_id='"+courseList.getValue(courseList.getSelectedIndex())+"' ";
					dataService.update(r, new AsyncCallback<Integer>()
					{
						public void onFailure(Throwable caught)
						{}

						public void onSuccess(Integer result)
						{
							String r ="delete from subject_course where course_id='"+courseList.getValue(courseList.getSelectedIndex())+"'";	
							dataService.update(r, new AsyncCallback<Integer>()
							{
								public void onFailure(Throwable caught)
								{}

								public void onSuccess(Integer result)
								{
									for (int i=0;i<tp.size();i++)
									{
										String r="insert into subject_course values('"+tp.get(i)+"','"+courseList.getValue(courseList.getSelectedIndex())+"')";
										dataService.insert(r, new AsyncCallback<Integer>()
										{
											public void onFailure(Throwable caught)
											{}

											public void onSuccess(Integer result)
											{
												courseCode.removeStyleName("error");
												courseName.removeStyleName("error");
												
											}
										});
									}
								}
							});		
						}
					});
				}
				else
				{
					if (courseCode.getText().equals(""))
						courseCode.addStyleName("error");
					else
						courseCode.removeStyleName("error");
					if (courseName.getText().equals(""))
						courseName.addStyleName("error");
					else
						courseName.removeStyleName("error");
				}
			}
		});
		courseList = new ListBox();
		courseList.addChangeHandler(new ChangeHandler()
		{
			public void onChange(ChangeEvent event)
			{
				updateCourseInfo(courseList.getValue(courseList.getSelectedIndex()));		
			}
		});
 		initListe();
		courseInfoPan.add(courseSubjectPan);
		courseInfoName.add(new HTML("Nom"));
		courseInfoName.add(courseName);
		courseInfoCode.add(new HTML("Code"));
		courseInfoCode.add(courseCode);

		courseLabel = new HorizontalPanel();
		courseLabel.add(courseInfoName);
		courseLabel.add(courseInfoCode);
		courseInfoPan.add(courseLabel);	
		courseInfoPan.add(courseValid);
		
		
		//Panel liste les Fiieres
		courseListPan.add(courseList);
		courseListPan.add(courseButton);
		
		
		//Ajout au panel général
		this.setHorizontalAlignment(ALIGN_CENTER);
		
		this.add(courseListPan);	
		this.add(courseInfoPan);
	
		
	
	}

	/**
	 * Fonction qui récupere et affiche les informations sur la filières séléctionnée
	 * @param id de la matière
	 */
	public void updateCourseInfo(final String id )
	{
		courseSubjectList.clear();
		courseSubjectWithList.clear();
		courseName.removeStyleName("error");
		courseCode.removeStyleName("error");
		validEnabled(true);
		
		
		String r="select subject_id,subject_name from subject where subject.subject_id not in (select subject_id from subject_course)";
		dataService.select(r, new AsyncCallback<HashMap<String,String[]>>()
		{
			public void onFailure(Throwable caught)
			{}

			public void onSuccess(HashMap<String, String[]> result)
			{
				for (int i=0;i<result.get("subject_id").length;i++)
					courseSubjectList.addItem(result.get("subject_name")[i],result.get("subject_id")[i]);
					
				String r="select * from course,subject,subject_course where course.course_id='"+id+"' and course.course_id=subject_course.course_id and subject.subject_id=subject_course.subject_id";
				dataService.select(r,new AsyncCallback<HashMap<String,String[]>>()
				{
					public void onFailure(Throwable caught)
					{}
				
					public void onSuccess(HashMap<String, String[]> result)
					{
						int isDel;
						for (int i=0;i<result.get("subject_id").length;i++)
						{
							isDel=-1;
							for (int j=0;j<courseSubjectList.getItemCount();j++)
							{
								if (courseSubjectList.getItemText(j).equals(result.get("subject_name")[i]))
									isDel=j;
							}
							courseSubjectWithList.addItem(result.get("subject_name")[i],result.get("subject_id")[i]);							
							if(isDel!=-1)
								courseSubjectList.removeItem(isDel);
						}	
						
						String r="select * from course where course_id='"+id+"'";
						dataService.select(r, new AsyncCallback<HashMap<String,String[]>>()
						{
							public void onFailure(Throwable caught)
							{}

							public void onSuccess(HashMap<String, String[]> result)
							{
								courseName.setText(result.get("course_name")[0]);
								courseCode.setText(result.get("course_code")[0]);
							}
						});	
					}
				});	
			}
		});	
	}
	
	/**
	 * Initialisation de la liste des matières
	 */
	public void initListe()
	{
		validEnabled(false);
		courseSubjectList.clear();
		courseSubjectWithList.clear();
		courseList.clear();
		courseList.setVisibleItemCount(10);
		courseList.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*2/3+"px");
		
		String r="select * from course ";
		dataService.select(r, new AsyncCallback<HashMap<String,String[]>>()
		{
			public void onSuccess(HashMap<String, String[]> result)
			{
				for (int i=0;i<result.get("course_id").length;i++)
				{
					//Window.alert(result.get("course_name")[i]+" , "+result.get("course_id")[i]);
					courseList.addItem(result.get("course_name")[i],result.get("course_id")[i]);
				}
			}
			
			public void onFailure(Throwable caught)
			{
				Window.alert("Select error : "+SERVER_ERROR);				
			}
		});
		
		
	}
	
	/**
	 * Fonction de redimensionnement
	 */
	public void onResize()
	{
		courseList.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*2/3+"px");
		courseSubjectList.setSize(Window.getClientWidth()*16/20*1/3+"px", Window.getClientHeight()*9/10*2/3+"px");
		courseSubjectWithList.setSize(Window.getClientWidth()*16/20*1/3+"px", Window.getClientHeight()*9/10*2/3+"px");
	}
	
	/**
	 * Fonction d'activation/desactivation des champs
	 * @param boolean
	 */
	public void validEnabled(boolean b)
	{
		courseName.setEnabled(b);
		courseCode.setEnabled(b);
		courseValid.setEnabled(b);
	}
}
